<?php

namespace app\admin\controller\expert;

use app\common\controller\Backend;
use fast\Tree;
use think\Cache;
use think\Db;

/**
 * 提现管理
 *
 * @icon   fa fa-list
 * @remark 
 */
class Withdraw extends Backend
{

    protected $searchFields = 'u.mobile';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 列表
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list_info = db("user_withdraw uw")
                ->join('user u', "uw.user_id=u.id", "LEFT")
                ->field("uw.*,u.nickname,u.avatar,u.mobile")
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            $list = $list_info->items();
            $total = $list_info->total();
            foreach ($list as $k => $v) {
                // exit(print_r($v));
                $list[$k]["avatar"] = $v["avatar"] ? cdnurl($v["avatar"], true) : letter_avatar($v["nickname"]);
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = Db::name("user_withdraw")->where(['id'=>$ids])->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 审核通过
     */
    public function confirm()
    {
        $ids = $this->request->param("ids");
        $user_withdraw = db("user_withdraw")->where("id", $ids)->find();
        if (!$user_withdraw) {
            $this->error("找不到记录");
        }

        $result = db("user_withdraw")->where("id", $user_withdraw["id"])->update(["status" => 1, "checktime" => time(), "note" => "审核通过"]);
        if ($result === false) {
            $this->error("更新审核失败");
        }
        $this->success("更新审核成功");
    }

    /**
     * 打款
     */
    public function pay()
    {
        $ids = $this->request->param("ids");
        $user_withdraw = db("user_withdraw")->where("id", $ids)->find();
        if (!$user_withdraw) {
            $this->error("找不到记录");
        }

        $result = db("user_withdraw")->where("id", $user_withdraw["id"])->update(["status" => 2, "paytime" => time(), "note" => "已打款"]);
        if ($result === false) {
            $this->error("更新打款失败");
        }
        $this->success("更新打款成功");
    }

    /**
     * 拒绝
     */
    public function refuse()
    {
        $ids = $this->request->param("ids");
        $note = $this->request->param("note");
        $user_withdraw = db("user_withdraw")->where("id", $ids)->find();
        if (!$user_withdraw) {
            $this->error("找不到记录");
        }
        if ($this->request->isPost()) {
            if($user_withdraw['status']!=0){
                $this->error("该记录已经处理！不能重复审核！");
            }
            // 启动事务
            Db::startTrans();
            try {
                $row = Db::name("user_withdraw")->where("id", $user_withdraw["id"])->update(["status" => 3, "checktime" => time(),  "note" => $note]);
                //返回金额给用户
                if($row==0){
                    throw new \Exception("更新新失败！");
                }
                $user = Db::name("user")->where(['id' => $user_withdraw['user_id']])->field("score")->find();
                if(empty($user)){
                    throw new \Exception("该用户不存在！");
                }
                
                $log = [];
                $log['before'] = $user['score'];
                Db::name('user')->where("id", $user_withdraw['user_id'])->data(["score" => ($user['score'] + $user_withdraw['money'])])->update();
                $log['titles'] = '驳回提现';
                $log['user_id'] = $user_withdraw['user_id'];
                $log['score'] = $user_withdraw['money'];
                $log['after'] = $user['score'] + $user_withdraw['money'];
                $log['createtime'] = time();
                $log['memo'] = '驳回提现';
                Db::name('user_score_log')->data($log)->insert();
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success("更新拒绝成功");
        }
        $this->view->assign('row', $user_withdraw);
        return $this->view->fetch();

    }
}
